<template>
  <div class="min-h-screen bg-gradient-to-b from-slate-50 to-slate-100 ui-modern">
    <!-- 顶部操作栏 -->
    <div class="bg-white/90 backdrop-blur border border-gray-100 rounded-xl shadow-sm px-6 py-4">
      <div class="w-full">
        <div class="flex items-center justify-end">
          <div class="flex items-center space-x-3">
            <div class="relative">
              <el-input 
                v-model="searchKey" 
                placeholder="搜索任务..." 
                class="w-80 search-input pill-input" 
                :prefix-icon="Search"
                @keyup.enter="handleSearch"
                clearable
              />
            </div>
            <el-select 
              v-model="status" 
              placeholder="状态筛选" 
              class="w-32 status-select pill-input" 
              @change="handleStatusChange"
              clearable
            >
              <el-option label="全部" :value="1" />
              <el-option label="已上线" :value="2" />
              <el-option label="待上线" :value="3" />
            </el-select>
            <el-date-picker 
              v-model="dateRange" 
              type="daterange" 
              range-separator="~" 
              start-placeholder="开始日期"
              end-placeholder="结束日期" 
              class="w-64 date-picker pill-input" 
              @change="handleDateChange" 
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
            <el-button 
              type="primary" 
              :icon="Search" 
              @click="handleSearch"
              class="search-btn btn-gradient !border-0 !rounded-full"
            >
              搜索
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="px-6 py-6">
      <div class="bg-white rounded-lg border border-gray-200 overflow-hidden">
        <el-table 
          :data="tableData" 
          style="width: 100%;" 
          max-height="700" 
          v-loading="loading"
          class="minimal-table modern-table table-bordered"
          border
          size="small"
          highlight-current-row
          @row-dblclick="openEditDialog"
          :header-cell-style="{ 
            background: '#f3f4f6', 
            color: '#0f172a', 
            fontWeight: '600',
            fontSize: '14px',
            borderBottom: '1px solid #d1d5db',
            whiteSpace: 'nowrap'
          }"
        >
          <el-table-column prop="onlineTaskName" label="任务名称" min-width="300" align="left">
        <template #default="{ row }">
          <div class="flex items-center space-x-3 py-2">
            <div class="flex-shrink-0">
                  <div :class="['w-2 h-2 rounded-full', getStatusDotClass(row.isOnlineTrue)]"></div>
            </div>
            <div class="flex-1 min-w-0">
              <div class="text-sm font-medium text-gray-900 truncate">
                {{ row.onlineTaskName }}
              </div>
              <div class="text-xs text-gray-500 mt-1">
                {{ getItemName(row.itemItemId) }}
              </div>
            </div>
            <div v-if="row.isSupplementaryOnlineTime === 2" class="flex-shrink-0">
              <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
                    补充
              </span>
            </div>
          </div>
        </template>
      </el-table-column>

          <el-table-column label="上线开始时间" width="220" align="center">
        <template #default="{ row }">
              <span>{{ formatToMinute(row.beginOnlineTime) || '未设置' }}</span>
        </template>
      </el-table-column>

          <el-table-column label="上线结束时间" width="220" align="center">
        <template #default="{ row }">
              <span>{{ formatToMinute(row.endOnlineTime) || '未设置' }}</span>
        </template>
      </el-table-column>

          <el-table-column label="上线状态" width="140" align="center">
        <template #default="{ row }">
              <el-tag :type="getOnlineStatusType(row.isOnlineTrue)">{{ getOnlineStatusText(row.isOnlineTrue) }}</el-tag>
        </template>
      </el-table-column>

          <el-table-column prop="onlineTaskCreateUserName" label="创建人" width="140" align="center">
        <template #default="{ row }">
          {{ row.onlineTaskCreateUserName }}
        </template>
      </el-table-column>

          <el-table-column label="上线问题" width="260" align="center">
        <template #default="{ row }">
              <span class="truncate block" :title="row.onlineIssues">{{ row.onlineIssues || '—' }}</span>
        </template>
      </el-table-column>

          <el-table-column label="失败原因" width="260" align="center">
        <template #default="{ row }">
              <span class="truncate block" :title="row.onlineFailureReasons">{{ row.onlineFailureReasons || '—' }}</span>
        </template>
      </el-table-column>

          <el-table-column label="是否计划内" width="120" align="center">
            <template #default="{ row }">
              <span :class="row.isPlanned === 1 ? 'text-green-600 font-medium' : (row.isPlanned === 2 ? 'text-red-600 font-medium' : 'text-gray-500')">
                {{ row.isPlanned === 1 ? '是' : (row.isPlanned === 2 ? '否' : '未设置') }}
              </span>
            </template>
          </el-table-column>

          <el-table-column label="是否延期" width="120" align="center">
            <template #default="{ row }">
              <span :class="row.isDelayed === 2 ? 'text-red-600 font-medium' : (row.isDelayed === 1 ? 'text-green-600 font-medium' : 'text-gray-500')">
                {{ row.isDelayed === 2 ? '是' : (row.isDelayed === 1 ? '否' : '未设置') }}
              </span>
            </template>
          </el-table-column>

          <el-table-column label="是否巡检" width="120" align="center">
            <template #default="{ row }">
              <span :class="row.isInspected === 2 ? 'text-red-600 font-medium' : (row.isInspected === 1 ? 'text-green-600 font-medium' : 'text-gray-500')">
                {{ row.isInspected === 2 ? '是' : (row.isInspected === 1 ? '否' : '未设置') }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="rollbackResponsiblePerson" label="回退责任人" width="180" align="center">
        <template #default="{ row }">
              <span>{{ row.rollbackResponsiblePerson || '—' }}</span>
        </template>
      </el-table-column>

          <el-table-column prop="planCreator" label="计划制定人" width="180" align="center">
        <template #default="{ row }">
              <span>{{ row.planCreator || '—' }}</span>
        </template>
      </el-table-column>

          <el-table-column prop="versionStatus" label="版本状态" width="160" align="center">
        <template #default="{ row }">
              <span :class="getVersionStatusClass(row.versionStatus)">{{ row.versionStatus || '未设置' }}</span>
        </template>
      </el-table-column>

          <el-table-column prop="responsiblePerson" label="责任人" width="160" align="center">
        <template #default="{ row }">
              <span>{{ row.responsiblePerson || '—' }}</span>
        </template>
      </el-table-column>

          <el-table-column label="关联需求" width="150" align="center">
        <template #default="{ row }">
              <el-button class="!rounded-button whitespace-nowrap btn-chip" @click="showRequirements(row)">
                {{ getRequirementCount(row) }} 个需求
          </el-button>
        </template>
      </el-table-column>

          <el-table-column label="参与人员" width="140" align="center">
        <template #default="{ row }">
              <el-button class="!rounded-button whitespace-nowrap btn-chip" @click="showParticipants(row)">
                {{ getParticipantsCount(row) }} 人
          </el-button>
        </template>
      </el-table-column>

          <el-table-column label="操作" width="140" fixed="right" align="center">
        <template #default="{ row }">
          <div class="flex items-center justify-center space-x-2">
            <button 
              @click="handleViewDetail(row)"
                  class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-gray-700 bg-white/80 border border-gray-200 rounded-full hover:bg-white focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
            >
              <el-icon class="w-3 h-3 mr-1">
                <View />
              </el-icon>
              查看
            </button>
          </div>
        </template>
      </el-table-column>
      </el-table>
      </div>
    </div>

    <!-- 翻页区域 -->
    <div class="px-6 py-4">
      <div class="flex items-center justify-between">
        <div class="text-sm text-gray-500">
          共 {{ total }} 条记录，第 {{ currentPage }} 页
        </div>
        <Pagination 
          :page-size="pageSize" 
          :total="total"
          @update:pageSize="handleSizeChange"
          @uadate:currentPage="handlePageChange"
        />
      </div>
    </div>

    <!-- 需求弹窗 -->
    <el-dialog 
      v-model="requirementsVisible" 
      title="关联需求" 
      width="1200px"
      class="minimal-dialog dialog-modern"
      :show-close="true"
      :close-on-click-modal="false"
    >
      <el-table :data="currentRequirements" style="width: 100%" class="minimal-table">
        <el-table-column prop="requirementName" label="需求名称" min-width="180" />
        <el-table-column prop="requirementRelevances" label="研发" width="120" />
        <el-table-column prop="contactTestNames" label="测试" width="120" />
        <el-table-column prop="beginTime" label="开始时间" width="160" />
        <el-table-column prop="endTime" label="结束时间" width="160" />
      </el-table>
    </el-dialog>

    <!-- 参与人弹窗 -->
    <el-dialog 
      v-model="participantsVisible" 
      title="参与人员" 
      width="800px"
      class="minimal-dialog dialog-modern"
      :show-close="true"
      :close-on-click-modal="false"
    >
      <el-table :data="currentParticipants" style="width: 100%" class="minimal-table">
        <el-table-column prop="bearUserName" label="姓名" min-width="120" />
        <el-table-column prop="bearType" label="角色" width="120">
          <template #default="{ row }">
            <el-tag :type="getRoleStatusType(row.bearType)">{{ getRoleName(row.bearType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="bearContent" label="负责内容" min-width="200" />
      </el-table>
    </el-dialog>

    <!-- 详情弹窗（仅展示列表字段，整齐两列排版） -->
    <el-dialog 
      v-model="detailVisible" 
      title="任务详情" 
      width="900px"
      class="minimal-dialog dialog-modern"
      :show-close="true"
      :close-on-click-modal="false"
    >
      <div v-if="currentTask" class="space-y-5">
        <div class="detail-grid">
          <div class="detail-item">
            <div class="detail-label">任务名称</div>
            <div class="detail-value font-semibold text-gray-900">{{ currentTask.onlineTaskName }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">创建人</div>
            <div class="detail-value">{{ currentTask.onlineTaskCreateUserName || '未设置' }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">上线开始时间</div>
            <div class="detail-value">{{ formatToMinute(currentTask.beginOnlineTime) || '未设置' }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">上线结束时间</div>
            <div class="detail-value">{{ formatToMinute(currentTask.endOnlineTime) || '未设置' }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">上线状态</div>
            <div class="detail-value"><el-tag :type="getOnlineStatusType(currentTask.isOnlineTrue)">{{ getOnlineStatusText(currentTask.isOnlineTrue) }}</el-tag></div>
          </div>
          <div class="detail-item">
            <div class="detail-label">是否计划内</div>
            <div class="detail-value"><span :class="currentTask.isPlanned === 1 ? 'text-green-600 font-medium' : (currentTask.isPlanned === 2 ? 'text-red-600 font-medium' : 'text-gray-500')">{{ currentTask.isPlanned === 1 ? '是' : (currentTask.isPlanned === 2 ? '否' : '未设置') }}</span></div>
          </div>
          <div class="detail-item">
            <div class="detail-label">是否延期</div>
            <div class="detail-value"><span :class="currentTask.isDelayed === 2 ? 'text-red-600 font-medium' : (currentTask.isDelayed === 1 ? 'text-green-600 font-medium' : 'text-gray-500')">{{ currentTask.isDelayed === 2 ? '是' : (currentTask.isDelayed === 1 ? '否' : '未设置') }}</span></div>
          </div>
          <div class="detail-item">
            <div class="detail-label">是否巡检</div>
            <div class="detail-value"><span :class="currentTask.isInspected === 2 ? 'text-red-600 font-medium' : (currentTask.isInspected === 1 ? 'text-green-600 font-medium' : 'text-gray-500')">{{ currentTask.isInspected === 2 ? '是' : (currentTask.isInspected === 1 ? '否' : '未设置') }}</span></div>
          </div>
          <div class="detail-item">
            <div class="detail-label">回退责任人</div>
            <div class="detail-value">{{ currentTask.rollbackResponsiblePerson || '未设置' }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">计划制定人</div>
            <div class="detail-value">{{ currentTask.planCreator || '未设置' }}</div>
          </div>
          <div class="detail-item">
            <div class="detail-label">版本状态</div>
            <div class="detail-value"><span :class="getVersionStatusClass(currentTask.versionStatus)">{{ currentTask.versionStatus || '未设置' }}</span></div>
          </div>
          <div class="detail-item">
            <div class="detail-label">责任人</div>
            <div class="detail-value">{{ currentTask.responsiblePerson || '未设置' }}</div>
          </div>
        </div>

        <div v-if="currentTask.onlineIssues && currentTask.onlineIssues.trim()">
          <label class="text-sm font-medium text-gray-600">上线问题</label>
          <p class="mt-2 p-4 bg-orange-50 rounded border text-orange-800">{{ currentTask.onlineIssues }}</p>
        </div>
        <div v-if="currentTask.onlineFailureReasons && currentTask.onlineFailureReasons.trim()">
          <label class="text-sm font-medium text-gray-600">失败原因</label>
          <p class="mt-2 p-4 bg-red-50 rounded border text-red-800">{{ currentTask.onlineFailureReasons }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑弹窗（双击行打开） -->
    <el-dialog 
      v-model="editVisible"
      title="编辑任务"
      width="720px"
      class="minimal-dialog dialog-modern"
      :show-close="true"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" label-width="110px" class="space-y-2">
        <el-form-item label="上线开始时间">
          <div class="flex items-center gap-3 w-full">
            <el-date-picker class="flex-1" v-model="editBeginDate" type="date" format="YYYY/M/D" value-format="YYYY-MM-DD" placeholder="选择日期" />
            <el-time-picker class="w-40" v-model="editBeginTime" format="HH:mm" value-format="HH:mm" placeholder="选择时间" />
      </div>
        </el-form-item>
        <el-form-item label="上线结束时间">
          <div class="flex items-center gap-3 w-full">
            <el-date-picker class="flex-1" v-model="editEndDate" type="date" format="YYYY/M/D" value-format="YYYY-MM-DD" placeholder="选择日期" />
            <el-time-picker class="w-40" v-model="editEndTime" format="HH:mm" value-format="HH:mm" placeholder="选择时间" />
      </div>
        </el-form-item>
        <el-form-item label="上线状态">
          <el-select v-model="editForm.isOnlineTrue" placeholder="选择状态" class="w-full">
            <el-option label="未设置" value="unset" />
            <el-option label="成功" value="success" />
            <el-option label="失败" value="fail" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editForm.isOnlineTrue !== 'success'" label="上线问题" :required="editForm.isOnlineTrue === 'fail'">
          <el-input v-model="editForm.onlineIssues" placeholder="输入问题" />
        </el-form-item>
        <el-form-item v-if="editForm.isOnlineTrue !== 'success'" label="失败原因" :required="editForm.isOnlineTrue === 'fail'">
          <el-input v-model="editForm.onlineFailureReasons" placeholder="输入原因" />
        </el-form-item>
        <el-form-item label="是否计划内">
          <el-select v-model="editForm.isPlanned" class="w-full" placeholder="未设置" clearable>
            <el-option label="是" :value="1" />
            <el-option label="否" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否延期">
          <el-select v-model="editForm.isDelayed" class="w-full" placeholder="未设置" clearable>
            <el-option label="是" :value="1" />
            <el-option label="否" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否巡检">
          <el-select v-model="editForm.isInspected" class="w-full" placeholder="未设置" clearable>
            <el-option label="是" :value="1" />
            <el-option label="否" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editForm.isOnlineTrue !== 'success'" label="回退责任人">
          <el-select
            v-model="editForm.rollbackResponsiblePersonUUID"
            multiple
            filterable
            :loading="guarantorLoading"
            placeholder="选择保障人员"
            class="w-full"
          >
            <el-option
              v-for="opt in guarantorOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划制定人">
          <el-select
            v-model="editForm.planCreatorUUID"
            filterable
            :loading="guarantorLoading"
            placeholder="选择计划制定人"
            clearable
            class="w-full"
          >
            <el-option
              v-for="opt in guarantorOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="版本状态">
          <el-select v-model="editForm.versionStatus" class="w-full" placeholder="选择状态">
            <el-option label="正常" value="正常" />
            <el-option label="项目经理异常" value="项目经理异常" />
            <el-option label="研发异常" value="研发异常" />
          </el-select>
        </el-form-item>
        <el-form-item label="责任人">
          <el-select
            v-model="editForm.responsiblePersonUUID"
            multiple
            filterable
            :loading="guarantorLoading"
            placeholder="选择责任人"
            class="w-full"
          >
            <el-option
              v-for="opt in guarantorOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" class="btn-gradient !border-0" @click="handleEditSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Search, View } from '@element-plus/icons-vue';
import { MyOfflineRequirement, UpdateMyOfflineRequirement } from "@/api/newDemands/index";
import { GetGetOnlineTaskRequirements, GetGetOnlineTaskMsg, GetGetOnlineTaskGuarantors } from "@/api/newDemands/index";
import { getItemList } from "@/api/common/index";
import Pagination from "@/components/Pagenation/index.vue";
import dayjs from 'dayjs';

const loading = ref(false);
const searchKey = ref('');
const status = ref(1);
const dateRange = ref<string[] | null>(null);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref<any[]>([]);

// 弹窗相关
const requirementsVisible = ref(false);
const participantsVisible = ref(false);
const detailVisible = ref(false);
const editVisible = ref(false);
const editBeginDate = ref<string>('');
const editBeginTime = ref<string>('');
const editEndDate = ref<string>('');
const editEndTime = ref<string>('');
const currentRequirements = ref<any[]>([]);
const currentParticipants = ref<any[]>([]);
const currentTask = ref<any>(null);
const allItems = ref<any[]>([]);
// 保障人员下拉
const guarantorOptions = ref<any[]>([]);
const guarantorLoading = ref(false);

// 搜索模式
const searchMode = ref({
  onlineTaskName: "",
  isOnlineTrue: "",
  page: 1,
  pageSize: 10,
  keyword: ""
});

// 获取角色名称
const getRoleName = (bearType: number) => {
  const roleMap: Record<number, string> = {
    1: "研发",
    2: "运维", 
    3: "测试"
  };
  return roleMap[bearType] || "未知";
};

// 获取角色状态Tag类型
const getRoleStatusType = (bearType: number) => {
  const typeMap: Record<number, string> = {
    1: "primary",
    2: "warning",
    3: "success"
  };
  return typeMap[bearType] || "info";
};

// 获取上线状态文案
const getOnlineStatusText = (st: string) => {
  const statusMap: Record<string, string> = {
    "unset": "未设置",
    "success": "成功",
    "fail": "失败"
  };
  return statusMap[st] || "未知";
};

// 获取上线状态Tag类型
const getOnlineStatusType = (st: string) => {
  const typeMap: Record<string, string> = {
    "unset": "info",
    "success": "success",
    "fail": "danger"
  };
  return typeMap[st] || "info";
};

// 版本状态提示（如需在其它地方复用可重新加入）
// const getVersionStatusTooltip = (st: string) => {
//   const tooltipMap: Record<string, string> = {
//     "正常": "版本状态正常",
//     "项目经理异常": "临时说某个需求不上线了就是项目经理异常",
//     "研发异常": "研发多带了就是研发异常"
//   };
//   return tooltipMap[st] || "版本状态说明";
// };

// 获取版本状态样式类
const getVersionStatusClass = (st: string) => {
  const classMap: Record<string, string> = {
    "正常": "text-green-600 font-medium",
    "项目经理异常": "text-orange-600 font-medium",
    "研发异常": "text-red-600 font-medium"
  };
  return classMap[st] || "text-gray-600";
};

// 获取责任人样式类（如需复用可打开）
// const getResponsiblePersonClass = () => "text-blue-600 font-medium cursor-help";

// 列表状态圆点颜色
const getStatusDotClass = (st: string) => {
  const map: Record<string, string> = {
    success: 'bg-green-500',
    fail: 'bg-red-500',
    unset: 'bg-gray-400'
  };
  return map[st] || 'bg-gray-400';
};

// 关联需求数量兜底逻辑
const getRequirementCount = (row: any) => {
  // 优先使用接口数组字段 onlieItemRequirements
  if (Array.isArray(row?.onlieItemRequirements)) return row.onlieItemRequirements.length;
  // 兼容其它命名
  if (Array.isArray(row?.requirements)) return row.requirements.length;
  // 兼容计数字段
  if (typeof row?.requirementsCount === 'number') return row.requirementsCount;
  const str = row?.requirementsCountStr || row?.requirementsCount || '';
  const num = Number(str);
  return Number.isFinite(num) ? num : 0;
};

// 参与人员数量兜底逻辑
const getParticipantsCount = (row: any) => {
  // 优先使用接口数组字段 onlineItemRequirementBearContent
  if (Array.isArray(row?.onlineItemRequirementBearContent)) return row.onlineItemRequirementBearContent.length;
  // 兼容其它命名
  if (Array.isArray(row?.bearContents)) return row.bearContents.length;
  // 兼容计数字段
  if (typeof row?.bearContentsCount === 'number') return row.bearContentsCount;
  const str = row?.bearContentsCountStr || row?.bearContentsCount || '';
  const num = Number(str);
  return Number.isFinite(num) ? num : 0;
};

// 格式化到分
const formatToMinute = (val: string) => {
  if (!val) return '';
  const d = dayjs(val);
  if (!d.isValid()) return val?.slice(0,16) || val;
  return d.format('YYYY-MM-DD HH:mm');
};

// 将后端以“|”分隔的UUID字符串转换为数组
const toArrayFromPipe = (val: any): string[] => {
  if (Array.isArray(val)) return val as string[];
  if (typeof val === 'string') {
    return val
      .split('|')
      .map((s: string) => s.trim())
      .filter((s: string) => !!s);
  }
  return [];
};

// 处理字段变更：已改为双击整行编辑，这里不再使用

// 搜索处理
const handleSearch = () => {
  searchMode.value.keyword = searchKey.value;
  searchMode.value.onlineTaskName = searchKey.value;
  currentPage.value = 1;
  getMyOfflineTasks();
};

// 状态变化处理（仅作为示例过滤字段传参）
const handleStatusChange = (val: number) => {
  if (val === 1) {
    searchMode.value.isOnlineTrue = "";
  } else if (val === 2) {
    // 根据实际后端约定调整：此处示例为“已上线”映射为 success
    searchMode.value.isOnlineTrue = "success";
  } else if (val === 3) {
    // 示例：待上线可以按未设置过滤
    searchMode.value.isOnlineTrue = "unset";
  }
  currentPage.value = 1;
  getMyOfflineTasks();
};

// 日期变化处理
const handleDateChange = () => {
  // 如需传参可在 searchMode 中补充 beginTime/endTime
  currentPage.value = 1;
  getMyOfflineTasks();
};

// 页面大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  getMyOfflineTasks();
};

// 页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
  getMyOfflineTasks();
};

// 显示需求
const showRequirements = async (row: any) => {
  try {
    const { data } = await GetGetOnlineTaskRequirements(row.ID);
    if (data.code === 200) {
      currentRequirements.value = data.data;
      requirementsVisible.value = true;
    } else {
      ElMessage.error(data.msg);
    }
  } catch (error) {
    ElMessage.error('获取需求列表失败');
  }
};

// 显示参与人员
const showParticipants = async (row: any) => {
  try {
    const { data } = await GetGetOnlineTaskMsg(row.ID);
    if (data.code === 200) {
      currentParticipants.value = data.data;
      participantsVisible.value = true;
    } else {
      ElMessage.error(data.msg);
    }
  } catch (error) {
    ElMessage.error('获取参与人员失败');
  }
};

// 查看详情
const handleViewDetail = (row: any) => {
  currentTask.value = row;
  detailVisible.value = true;
};

// 编辑任务：已改为双击整行打开弹窗

// 双击行打开编辑
const editForm = ref<any>({});
const openEditDialog = (row: any) => {
  editForm.value = { ...row };
  // 拆分日期与时间，便于分别编辑
  editBeginDate.value = row.beginOnlineTime ? row.beginOnlineTime.slice(0, 10) : '';
  editBeginTime.value = row.beginOnlineTime ? row.beginOnlineTime.slice(11, 16) : '';
  editEndDate.value = row.endOnlineTime ? row.endOnlineTime.slice(0, 10) : '';
  editEndTime.value = row.endOnlineTime ? row.endOnlineTime.slice(11, 16) : '';
  // 回显：将“|”分隔字符串转换为数组
  editForm.value.rollbackResponsiblePersonUUID = toArrayFromPipe(row.rollbackResponsiblePersonUUID);
  editForm.value.responsiblePersonUUID = toArrayFromPipe(row.responsiblePersonUUID);
  editForm.value.planCreatorUUID = Array.isArray(row.planCreatorUUID)
    ? row.planCreatorUUID[0] || ''
    : (typeof row.planCreatorUUID === 'string' ? row.planCreatorUUID : '');
  // 将 0 正常化为 undefined，避免下拉显示为 0
  const normalizeChoice = (v: any) => (v === 1 || v === 2 ? v : undefined);
  editForm.value.isPlanned = normalizeChoice(row.isPlanned);
  editForm.value.isDelayed = normalizeChoice(row.isDelayed);
  editForm.value.isInspected = normalizeChoice(row.isInspected);
  // 每次打开都刷新一次，确保列表最新
  loadGuarantors();
  editVisible.value = true;
};

// 加载保障人员列表
const loadGuarantors = async () => {
  guarantorLoading.value = true;
  try {
    const { data } = await GetGetOnlineTaskGuarantors();
    if (data.code === 200) {
      const raw = data.data;
      const list = Array.isArray(raw) ? raw : (Array.isArray(raw?.list) ? raw.list : []);
      guarantorOptions.value = list.map((it: any) => {
        const label = it.userName || it.nickName || it.name || it.label || it.realName || '未知';
        const value = it.uuid || it.UUID || it.userUUID || it.userUuid || it.value || it.id || it.ID || '';
        return { label, value };
      }).filter((o: any) => o.value);
    }
  } catch (e) {
    // ignore
  } finally {
    guarantorLoading.value = false;
  }
};

// 确认保存（本地更新，实际可改为请求后端）
const handleEditSave = async () => {
  if (!editForm.value?.ID) {
    editVisible.value = false;
    return;
  }
  // 必填校验：当状态为失败时，上线问题与失败原因不能为空
  if (editForm.value.isOnlineTrue === 'fail') {
    const issue = (editForm.value.onlineIssues || '').trim();
    const reason = (editForm.value.onlineFailureReasons || '').trim();
    if (!issue || !reason) {
      ElMessage.error('选择失败时，必须填写“上线问题”和“失败原因”');
      return;
    }
  }
  // 组装请求体（与后端定义保持一致）
  // 将拆分的日期与时间重新拼接
  const beginOnlineTime = editBeginDate.value && editBeginTime.value
    ? `${editBeginDate.value} ${editBeginTime.value}:00`
    : '';
  const endOnlineTime = editEndDate.value && editEndTime.value
    ? `${editEndDate.value} ${editEndTime.value}:00`
    : '';
  const payload = {
    id: editForm.value.ID,
    isOnlineTrue: editForm.value.isOnlineTrue ?? 'unset',
    onlineIssues: editForm.value.onlineIssues ?? '',
    onlineFailureReasons: editForm.value.onlineFailureReasons ?? '',
    isPlanned: editForm.value.isPlanned === 1 || editForm.value.isPlanned === 2 ? Number(editForm.value.isPlanned) : 0,
    isDelayed: editForm.value.isDelayed === 1 || editForm.value.isDelayed === 2 ? Number(editForm.value.isDelayed) : 0,
    isInspected: editForm.value.isInspected === 1 || editForm.value.isInspected === 2 ? Number(editForm.value.isInspected) : 0,
    rollbackResponsiblePersonUUID: Array.isArray(editForm.value.rollbackResponsiblePersonUUID) ? editForm.value.rollbackResponsiblePersonUUID : [],
    planCreatorUUID: editForm.value.planCreatorUUID || '',
    versionStatus: editForm.value.versionStatus ?? '',
    responsiblePersonUUID: Array.isArray(editForm.value.responsiblePersonUUID) ? editForm.value.responsiblePersonUUID : [],
    beginOnlineTime,
    endOnlineTime
  };
  try {
    const { data } = await UpdateMyOfflineRequirement(payload as any);
    if (data.code === 200) {
      // 先本地更新，再主动刷新列表，确保与后端数据一致
      const idx = tableData.value.findIndex((it: any) => it.ID === editForm.value.ID);
  if (idx !== -1) {
        tableData.value[idx] = {
          ...tableData.value[idx],
          ...editForm.value,
          // 同步显示字段，便于列表立即回显
          rollbackResponsiblePerson: (guarantorOptions.value
            .filter((o: any) => editForm.value.rollbackResponsiblePersonUUID?.includes(o.value))
            .map((o: any) => o.label)).join('|'),
          planCreator: (guarantorOptions.value.find((o: any) => o.value === editForm.value.planCreatorUUID)?.label) || tableData.value[idx].planCreator
        };
      }
      editVisible.value = false;
      await getMyOfflineTasks();
      ElMessage.success('已保存修改并已刷新');
    } else {
      ElMessage.error(data.msg || '保存失败');
    }
  } catch (e) {
    ElMessage.error('保存失败');
  }
};

// 获取项目名称
const getItemName = (itemId: number) => {
  if (!allItems.value || allItems.value.length === 0) {
    return "未知项目";
  }
  const item = allItems.value.find((itm: any) => itm.ID === itemId);
  return item ? item.itemName : "未知项目";
};

// 获取所有项目列表
const getAllItems = async () => {
  try {
    const { data } = await getItemList();
    if (data.code === 200) {
      allItems.value = data.data || [];
    }
  } catch (error) {
    console.error('获取项目列表失败:', error);
  }
};

// 获取我的上线任务列表
const getMyOfflineTasks = async () => {
  loading.value = true;
  searchMode.value.page = currentPage.value;
  searchMode.value.pageSize = pageSize.value;
  try {
    const { data } = await MyOfflineRequirement(searchMode.value);
    if (data.code === 200) {
      tableData.value = data.data.list || [];
      total.value = data.data.total || 0;
    } else {
      ElMessage.error(data.msg);
    }
  } catch (error) {
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 页面初始化
onMounted(async () => {
  await getAllItems();
  getMyOfflineTasks();
});
</script>

<style scoped>
/* 极简风格样式 */

/* 新增：整体现代UI变量 */
.ui-modern {
  --grad-from: #6366f1;
  --grad-to: #8b5cf6;
}

/* 胶囊输入外观 */
.pill-input :deep(.el-input__wrapper) {
  border-radius: 9999px;
  background: #ffffff;
}

/* 渐变主按钮 */
.btn-gradient {
  background-image: linear-gradient(90deg, var(--grad-from), var(--grad-to));
}
.btn-gradient:hover {
  filter: brightness(1.05);
}
.btn-gradient:active {
  filter: brightness(0.98);
}

/* 轻量Chip按钮 */
.btn-chip {
  border-radius: 9999px;
  border: 1px solid #e5e7eb;
  background: #fff;
}
.btn-chip:hover {
  background: #f9fafb;
}

/* 表格现代外观 */
.modern-table :deep(.el-table__header th) {
  background: #ffffff !important;
}
.modern-table :deep(.el-table__header th .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.modern-table :deep(.el-table__body td) {
  border-bottom: 1px solid #eef2f7;
}

/* 紧凑边框风格定制 */
.table-bordered :deep(.el-table) {
  --el-table-border-color: #e5e7eb;
}
.table-bordered :deep(.el-table__inner-wrapper::before) {
  background-color: #e5e7eb;
}
.table-bordered :deep(.el-table__body td),
.table-bordered :deep(.el-table__header th) {
  border-right: 1px solid #e5e7eb;
}
.table-bordered :deep(.el-table__row.hover-row > td),
.table-bordered :deep(.el-table__row.current-row > td) {
  background: #eef2ff !important; /* 高亮更明显 */
}

/* 表头与内容文字增强对比 */
.modern-table :deep(.el-table__header th) {
  color: #0f172a !important;
}
.modern-table :deep(.el-table__body td) {
  color: #1f2937;
}

/* Tag 与选择器颜色增强 */
.modern-table :deep(.el-tag--success) { background-color: #d1fae5; color: #065f46; border-color: #10b981; }
.modern-table :deep(.el-tag--danger) { background-color: #fee2e2; color: #991b1b; border-color: #ef4444; }
.modern-table :deep(.el-tag--info) { background-color: #e5e7eb; color: #374151; border-color: #9ca3af; }

/* 弹窗现代外观 */
.dialog-modern :deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
}
.dialog-modern :deep(.el-dialog__header) {
  background: linear-gradient(90deg, #f8fafc, #ffffff);
}

/* 详情模态-两列整齐排布 */
.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 16px 24px;
}
.detail-item {
  background: #ffffff;
  border: 1px solid #eef2f7;
  border-radius: 8px;
  padding: 12px 14px;
}
.detail-label {
  font-size: 12px;
  color: #6b7280;
}
.detail-value {
  margin-top: 6px;
  font-size: 14px;
  color: #111827;
}

/* 搜索输入框 */
.search-input :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #d1d5db;
  box-shadow: none;
  transition: all 0.2s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: #9ca3af;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* 状态选择器 */
.status-select :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #d1d5db;
  box-shadow: none;
  transition: all 0.2s ease;
}

.status-select :deep(.el-input__wrapper):hover {
  border-color: #9ca3af;
}

/* 日期选择器 */
.date-picker :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #d1d5db;
  box-shadow: none;
  transition: all 0.2s ease;
}

.date-picker :deep(.el-input__wrapper):hover {
  border-color: #9ca3af;
}

/* 搜索按钮 */
.search-btn {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s ease;
}

/* 表格样式 */
.minimal-table :deep(.el-table__header th) {
  background: #f8fafc;
  color: #374151;
  font-weight: 600;
  font-size: 14px;
  border: none;
  padding: 12px 16px;
}

.minimal-table :deep(.el-table__body tr) {
  transition: background-color 0.2s ease;
}

.minimal-table :deep(.el-table__body tr:hover) {
  background-color: #f9fafb;
}

.minimal-table :deep(.el-table__body td) {
  border: none;
  padding: 12px 16px;
  border-bottom: 1px solid #f3f4f6;
}

/* 弹窗样式 */
.minimal-dialog :deep(.el-dialog) {
  border-radius: 8px;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
  border: 1px solid #e5e7eb;
}

.minimal-dialog :deep(.el-dialog__header) {
  background: #f8fafc;
  color: #374151;
  padding: 16px 20px;
  border-bottom: 1px solid #e5e7eb;
  border-radius: 8px 8px 0 0;
}

.minimal-dialog :deep(.el-dialog__title) {
  color: #374151;
  font-weight: 600;
  font-size: 16px;
}

.minimal-dialog :deep(.el-dialog__close) {
  color: #6b7280;
  font-size: 18px;
}

.minimal-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

/* 输入框和选择器通用样式 */
.el-input :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #d1d5db;
  box-shadow: none;
  transition: all 0.2s ease;
}

.el-input :deep(.el-input__wrapper):hover {
  border-color: #9ca3af;
}

.el-input :deep(.el-input__wrapper.is-focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.el-select :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #d1d5db;
  box-shadow: none;
  transition: all 0.2s ease;
}

.el-select :deep(.el-input__wrapper):hover {
  border-color: #9ca3af;
}

/* 日期选择器隐藏图标（示例） */
input[type="date"]::-webkit-calendar-picker-indicator {
  display: none;
}

/* 响应式设置 */
@media (max-width: 768px) {
  .grid-cols-1.md\:grid-cols-2 {
    grid-template-columns: 1fr;
  }
  
  .flex.items-center.space-x-3 {
    flex-direction: column;
    gap: 12px;
  }
  
  .w-80, .w-64, .w-32 {
    width: 100%;
  }
}
</style>

